<template>
	<view class="relative full-screen">
		<view
			style="z-index:0;position:absolute;left:0;right:0;top:0;height:317px;background:linear-gradient(180deg, #FA4543 0%, #FA4D40 78.95%, #FCB513 100%);">
		</view>
		<uni-nav-bar ref="navBar" statusBar :border="false" backgroundColor="transparent" @clickLeft="goBack">
			<template v-slot:left>
				<image class="size-32" src="@/static/svg/icon-back.svg" />
			</template>
			<view class="flex center w-full fs-16"><text class="text-white">拼团详情</text></view>
		</uni-nav-bar>
		<view v-if="detail" class="flex-col" :style="`height: calc(100vh - ${navBarHeight || 0}px);`">
			<view class="relative radius-12 bg-white mx-16 mt-16 px-12 py-16 fs-14" style="z-index:1;"
				:style="detail.activeState === 4 ? 'filter:brightness(0.8);' : ''" @click="toBuy">
				<view class="flex">
					<view class="relative mr-12 flex-shrink">
						<image class="radius-8" style="width:88px;height:88px;" :src="coverPicture"></image>
					</view>
					<view class="flex-1 w-0">
						<view class="font-semibold">
							<tag class="mr-4">{{ promotionLabel }}</tag>
							{{ detail.activeTitle }}
						</view>
						<view class="flex align-end mt-8">
							<view class="flex color-primary mr-8 leading-22" style="align-items:baseline;">
								<text>¥</text>
								<text class="font-semibold fs-21">
									{{ numberFormat(detail.groupBuyPrice) }}</text>
							</view>
							<view class="flex text-color-hint text-throughline mr-16 leading-22"
								style="align-items:baseline;">
								<text>¥</text><text class="font-medium">{{ numberFormat(detail.activePrice) }}</text>
							</view>
						</view>
					</view>
				</view>
				<view v-if="orderInfo && orderInfo.activeStepPrices && orderInfo.activeStepPrices.length" class="mt-8">
					<sign-up-number-tag v-for="(item, index) in orderInfo.activeStepPrices" :key="index"
						:number="item.enrollNum" :price="item.enrollPrice" class="mr-8" />
				</view>
				<image v-if="isActivityExpired" class="absolute" style="width:60px;height:60px;bottom:12px;right:12px;"
					src="@/pagesA/static/svg/finished.svg">
				</image>
			</view>
			<view class="mt-8 radius-12 bg-white mx-16" style="z-index:1;">
				<view v-if="status !== 'success' && remainEndTimeInfo && !remainEndTimeInfo.isEnd"
					class="flex center fs-13 py-12" style="height: 44px;">
					<text>活动将于</text>
					<text class="radius-4 w-20 h-20 flex center bg-primary text-white mx-3">
						{{ remainEndTimeInfo.day }}</text>
					<text>天</text>
					<text class="radius-4 w-20 h-20 flex center bg-primary text-white ml-3">
						{{ remainEndTimeInfo.hour }}</text>
					<image class="mx-6 w-2 h-7" src="@/pagesA/static/svg/colon.svg"></image>
					<text class="radius-4 w-20 h-20 flex center bg-primary text-white">
						{{ remainEndTimeInfo.min }}</text>
					<image class="mx-6 w-2 h-7" src="@/pagesA/static/svg/colon.svg"></image>
					<text class="radius-4 w-20 h-20 flex center bg-primary text-white mr-3">
						{{ remainEndTimeInfo.sec }}</text>
					<text>结束</text>
				</view>

				<view class="pb-16">
					<view v-if="status === 'inprogress'" class="pt-16 flex justify-center text-color-hint fs-18 c3">
						还差 <view class="color-primary">{{ detail.groupNum - detail.members.length }}</view>人，快邀请小伙伴吧~
					</view>
					<view v-else-if="status === 'success'"
						class="flex justify-center flex-wrap text-color-hint fs-18 c3">
						<view class="w-full text-bold text-center mb-20 bg-image">拼团成功</view>
						<view class="c3-6 fs-12 w-full text-center">
							{{ isOneOfMember ? '恭喜，组团成功':'来晚了，已满员' }}
						</view>
					</view>
					<view v-else class="flex justify-center flex-wrap text-color-hint fs-18 c3">
						<view class="w-full text-bold text-center mb-20 bg-image">拼团已过期</view>
						<view class="c3-6 fs-12 w-full text-center">组团失败</view>
					</view>

					<view class="flex justify-center mt-24 px-16">
						<template v-if="detail.groupNum <= 8">
							<badge v-for="(avatarItem, ind) in detail.members" :key="`member_${ind}`" class="w-50 h-50"
								:show="!!avatarItem.groupLead" :style="{ 'margin-left': ind ? memberAvatarMarginLeft : 0 }">
								<image :src="avatarItem.avatar" class="w-50 h-50 cu-avatar round"
									style="border:0.5px solid #fff">
								</image>
							</badge>
							<image v-if="detail.groupNum !== detail.members.length" class="w-49 h-49  round"
								src="@/pagesA/static/svg/invite-user.svg"
								:style="{ 'margin-left': detail.members.length ? memberAvatarMarginLeft : 0, 'border': '0.5px solid #fff' }">
							</image>
						</template>
						<template v-else>
							<view class="mr-20 flex" style="flex-direction:row-reverse;">
								<badge v-for="(item, i) in detail.members.filter((_, j) => j < 8)" :key="`member_${i}`"
									class="w-50 h-50" :show="!!item.groupLead"
									:style="{ 'margin-left': ind ? memberAvatarMarginLeft : 0 }">
									<image :src="item.avatar" class="w-50 h-50 cu-avatar round"
										style="border:0.5px solid #fff">
									</image>
								</badge>
							</view>
							<image v-if="detail.groupNum !== detail.members.length" class="w-49 h-49 round"
								src="@/pagesA/static/svg/invite-user.svg"
								:style="{ 'margin-left': detail.members.filter((_, j) => j < 8).length ? '-30px' : 0, 'border': '0.5px solid #fff' }">
							</image>
						</template>
					</view>

					<view class="flex justify-between mb-16">
						<template v-if="isDirectJoin && status === 'inprogress' && !isOneOfMember">
							<view class="mt-28 mx-12 relative w-full">
								<view v-if="detail.freeType === 2" class="fs-12 text-white text-center w-full absolute"
									style="background-color: #FF7978;top: -19px; height: 41px;border-top-left-radius:20px;border-top-right-radius:20px;">
									<view class="h-18 flex item-center justify-center">拼团抽免单</view>
								</view>
								<view class="px-24 h-38 bg-primary flex center text-white fs-16 relative z-1"
									style="border-radius:36px;flex: 1 1 50%;" @click="toJoin">
									立即参团
								</view>
							</view>
						</template>

						<template v-else>
							<view v-if="!isActivityExpired"
								class="mt-28 mx-12 px-24 h-38 bg-white border-secondary-warning flex center color-secondary-warning fs-16"
								style="border-radius:36px;flex: 1 1 50%;" @click="toBuy">
								{{ detail.groupLeadState ? '再开一团' : '我也要开团' }}
							</view>
							<view v-if="status === 'inprogress' && detail.inviteEnable" class="mt-28 mx-12 relative"
								style="flex: 1 1 50%;">
								<view v-if="detail.freeType === 2" class="fs-12 text-white text-center w-full absolute"
									style="background-color: #FF7978;top: -19px; height: 41px;border-top-left-radius:20px;border-top-right-radius:20px;">
									<view class="h-18 flex item-center justify-center">拼团抽免单</view>
								</view>
								<view class="px-24 h-38 bg-primary flex center text-white fs-16 relative z-1"
									style="border-radius:36px;white-space: nowrap;" @click="toInvite">
									邀请好友拼团
								</view>
							</view>
							<view v-if="showViewOrder"
								class="mt-28 mx-12 px-24 h-38 bg-primary flex center text-white fs-16"
								style="border-radius:36px;flex: 1 1 50%;" @click="toOrder">
								查看订单
							</view>
						</template>
					</view>

					<view v-if="detail.groupLeadState"
						class="relative flex justify-center item-center mt-0 mx-16 text-color-regular"
						@click="viewMembers">
						<text class="fs-12 font-semibold text-color-hint">查看参团成员 ></text>
					</view>

				</view>
			</view>
			<recommend :activeId="activeId" :businessId="businessId" />
			<share-activity v-if="showSharePopup" :id="activeId" :show="showSharePopup" :ext-params="sharedExtParams"
				type="inviteGroupBuy" :not-promotion-incentive="true" @onClose="showSharePopup = false" :options="{groupBuyLabel:promotionLabel}" />
			<GroupBuyOrderPopup v-if="activityDetail" ref="groupBuyOrderPopupIns" :data="activityDetail" :code="code"
				:group-buy-order-id="groupBuyOrderId" :is-zero-group-buy="false" />
		</view>
	</view>
</template>

<script setup>
import { onLoad, onShareAppMessage, onShow } from '@dcloudio/uni-app'
import {
	computed,
	ref,
} from 'vue'
import { groupBuyOrderDetailApi } from '@/api/order.js'
import { activeUpdateEnd,activeDetailsApi } from '@/api/activity.js'
import { numberFormat, formatEndTime, toRouterParamsStr,parseScene } from '@/utils/index.js'
import { useOrder } from '@/hooks/useOrder.js'
import Tag from '@/components/tag/tag.vue'
import GroupBuyOrderPopup from '@/pagesB/activity/components/group-buy-order-popup.vue'
import Badge from '../components/badge/badge.vue'
import Recommend from '@/pagesF/components/recommend/recommend.vue'
import { useUserStore } from '@/stores/modules/user.js'

const userStore = useUserStore()
const businessId = computed(() => {
	return `${userStore.userInfo?.businessInfo?.id || ''}`;
})
const isOneOfMember = computed(()=>{
	if(userStore.userInfo?.id && detail.value){
		return !!detail.value.members.find(item=>item.userId===userStore.userInfo.id);
	}
	return false;
});
const isGroupLead = computed(()=>{
	if(userStore.userInfo?.id && detail.value){
		const member = detail.value.members.find(item=>item.userId===userStore.userInfo.id);
		return !!member?.groupLead;
	}
	return false;
});

const id = ref(null)
const detail = ref(null)
const isActivityExpired = computed(() => {
	return !formatEndTime(detail.value?.activeEndTime);
})
const { orderInfo, updateOrderInfo, coverPicture, remainEndTime } = useOrder()

const navBar = ref(null)
const navBarHeight = computed(() => {
	const statusBarHeight = uni.getWindowInfo().statusBarHeight
	const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
	return navigationBarHeight
})

const memberAvatarMarginLeft = computed(()=>{
	let memberCount = detail.value.members?.length || 0;
	memberCount = memberCount > 8 ? 10 : memberCount;
	if(memberCount){
		const screenWidth = uni.getWindowInfo().screenWidth;
		const awatarContainerWidth = screenWidth - (16+16)*2;
		const maxNum = Math.floor(awatarContainerWidth/50);

		if(maxNum < memberCount){
			return `-${(memberCount-maxNum)*15/maxNum}px`;
		}
	}

	return 0;
})

const showViewOrder = computed(()=>{
	if(status.value !== 'success') return false;
	if(!isOneOfMember.value) return false;
	if(isGroupLead.value && activityDetail.value && activityDetail.value.leadFreeEnabled===1) return false;
	return true;
})

const goBack = () => {
	if (getCurrentPages().length === 1) {
		uni.reLaunch({
			url: '/pages/home/home'
		})
		return
	}
	uni.navigateBack()
}

const remainEndTimeInfo = ref(null)
const endTimeCounter = () => {
	if (remainEndTimeInfo.value?.isEnd) return;
	setTimeout(() => {
		remainEndTimeInfo.value = remainEndTime()
		if (remainEndTimeInfo.value.day <= 0
			&& remainEndTimeInfo.value.hour <= 0
			&& remainEndTimeInfo.value.min <= 0
			&& remainEndTimeInfo.value.sec <= 0) {
			remainEndTimeInfo.value.isEnd = true
		}
		if (!remainEndTimeInfo.value.isEnd) {
			endTimeCounter()
		} else {
			// 活动结束时间已到，通知服务端更新状态
			activeUpdateEnd({
				id: id.value,
				activeState: 4
			}).then(() => {
				getDetail()
			})
		}
	}, 1000)
}

const promotionLabel = computed(() => {
	return detail.value ? `${detail.value.groupNum}人团` : '';
});

const status = computed(() => {
	if (!detail.value) return '';

	if (detail.value.members.length < detail.value.groupNum) {
		return remainEndTimeInfo.value?.isEnd ? 'failure' : 'inprogress';
	};

	return 'success';
});

const signResultTitle = computed(() => {
	let str = detail.value.title
	const regex = /\d+/g
	str = str.replace(/(\d*\.?\d+)/g, function (match, val, index) {
		if (index > 2) {
			return `<span class="color-primary">${match}</span>`
		} else {
			return `<span class="color-primary">${match}</span>`
		}
	})
	return str
})

const isLoadingDetail = ref(false);
const getDetail = () => {
	if(isLoadingDetail.value) return;

	const params = {};
	if (id.value) {
		params.orderId = id.value;
	}
	if (groupBuyOrderItemId.value) {
		params.groupBuyOrderItemId = groupBuyOrderItemId.value;
	}
	if (groupBuyOrderId.value) {
		params.groupBuyOrderId = groupBuyOrderId.value;
	}

	uni.showLoading();
	isLoadingDetail.value = true;
	groupBuyOrderDetailApi(params,{linkParamsUrl:linkParamsUrl.value}).then(res => {
		res.endTime = res.expiredTime;
		detail.value = res
		updateOrderInfo(res)
		endTimeCounter();
		
		// 要先执行，否则下方的linkParamsUrl会被覆盖掉
		userStore.getUserInfo();
	}).finally(() => {
		isLoadingDetail.value = false;
		setTimeout(() => {
			uni.hideLoading()
		}, 500);
	});
}

const viewMembers = () => {
	uni.navigateTo({
		url: `/pagesG/order/view-group-buy-members?id=${id.value}&groupBuyOrderId=${detail.value.groupBuyOrderId}`
	})
}

const showSharePopup = ref(false)
const sharedExtParams = ref();
const toInvite = () => {
	sharedExtParams.value = {
		groupBuyOrderId: detail.value.groupBuyOrderId
	};
	showSharePopup.value = true;
}

const toBuy = () => {
	uni.navigateTo({
		url: `/pagesB/activity/activity-group-buy?id=${activeId.value}`
	})
}

const toOrder = () => {
	uni.navigateTo({
		url: `/pagesA/order/order-detail?id=${id.value}&type=1`
	})
}

const toPay = () => {
	uni.navigateTo({
		url: `/pagesA/order/wait-pay?id=${detail.value.orderId}`,
		events: {
			// TODO 支付成功后
		}
	})
}

const groupBuyOrderPopupIns = ref(null);
const toJoin = () => {
	groupBuyOrderPopupIns.value.show(true)
};

const activityDetail = ref();
const getActivityDetail = ()=>{
	activeDetailsApi(activeId.value).then(res=>{
		activityDetail.value = res;
	})
};

onShow(() => {
	getDetail()
})

const activeId = ref();
const groupBuyOrderItemId = ref();
const isDirectJoin = ref(false);
const code = ref('');
const groupBuyOrderId = ref();
const linkParamsUrl = ref();
onLoad((options) => {
	console.log(options)
	
	linkParamsUrl.value = `from=${encodeURIComponent(`/pagesA/order/group-buy-detail${toRouterParamsStr(options)}`)}`;
	
	id.value = options.id || ''
	activeId.value = options.activeId || '';
	groupBuyOrderItemId.value = options.groupBuyOrderItemId || undefined;
	isDirectJoin.value = options.isDirectJoin === 'true';
	code.value = options.code||'';
	groupBuyOrderId.value = options.groupBuyOrderId||'';

	// 扫码打开
	if (options.scene) {
		const scene = parseScene(options.scene)
		if (!options.activeId && scene.aId) {
			activeId.value = scene.aId
			code.value = scene.code
		}
		if (!options.groupBuyOrderId && scene.gId) {
			groupBuyOrderId.value = scene.gId
		}
	}

	if (id.value || groupBuyOrderItemId.value || groupBuyOrderId.value) {
		getDetail()
	}
	if(activeId.value){
		getActivityDetail();
	}
})

onShareAppMessage((options) => {
	console.log('活动详情分享', options)
	showSharePopup.value = false
	if (options.from === 'button') {
		const url = '/pagesA/order/group-buy-detail';
		const idParamStr = id.value?`id=${id.value}`:`groupBuyOrderItemId=${groupBuyOrderItemId.value}`
		return {
			title: options.target.dataset.title,
			path: `${url}?${idParamStr}&activeId=${activeId.value}&isDirectJoin=true&groupBuyOrderId=${detail.value.groupBuyOrderId}`,
			imageUrl: options.target.dataset.filepath
		}
	}
})
</script>
<style lang="scss" scoped>
.bg-image {
	width: 100%;
	height: 44px;
	display: flex;
	justify-content: center;
	align-items: center;
	background-image: url('https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-Group%201031.png');
	background-size: 100% 100%;
}
</style>